from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter
from drf_haystack.viewsets import HaystackViewSet

from .models import SKU
from .serializers import SKUSerializer, SKUIndexSerializer
# Create your views here.



# /categories/(?P<category_id>\d+)/skus?page=xxx&page_size=xxx&ordering=xxx
class SKUListView(ListAPIView):
    """商品列表页：分页和排序"""

    # 指定查询集：需要展示的列表数据，需要根绝条件过滤,category_id需要对应，还有必须是未下架的商品
    # queryset = SKU.objects.all()

    # 指定序列化器
    serializer_class = SKUSerializer

    # 这种写法，只对这个视图的分页有效
    # pagination_class = '自定义的分页类，自己制定分页规则'

    # 指定排序和过滤的后端:ordering=price(根据价格小到大) ordering=-price(根据价格大到小)
    filter_backends = [OrderingFilter]
    # 指定排序和过滤的字段:create_time=根据记录的时间排序，price=根据价格排序，sales=根据销量排序
    ordering_fields = ('create_time', 'price', 'sales')

    def get_queryset(self):
        """根据条件刷选出需要展示在列表界面的数据"""
        category_id = self.kwargs.get('category_id')
        return SKU.objects.filter(category_id=category_id, is_launched=True)

class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer